import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class PdfboxTest {
    public static void main(String[] args) throws IOException {

        String input = "D:\\pdf-for-test\\图片表格类型.pdf";

        String password = "123456";
        PDDocument document = Loader.loadPDF(new File(input));

        // 一次性获取全部文本
        PDFTextStripper stripper = new PDFTextStripper();
        String content = stripper.getText(document);
        System.out.println(content);

// 按页码获取内容
//        for (int i = 0; i < document.getNumberOfPages(); i++) {
//            PDPage page = document.getPage(i);
//            // 处理每一页
//            handlePage(page, i, document);
//        }

        document.close();
        System.out.println("done");
    }

    static void handlePage(PDPage page, int pageNumber, PDDocument document) throws IOException {
        System.out.println("handlePage");


        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setStartPage(pageNumber + 1);
        stripper.setEndPage(pageNumber + 1);
        String text = stripper.getText(document);

        System.out.println("pageNumber" + pageNumber);
        System.out.println(text);

        PDResources resources = page.getResources();
        for (COSName name : resources.getXObjectNames()) {
            PDXObject xobject = resources.getXObject(name);
            if (xobject instanceof PDImageXObject) {
                PDImageXObject image = (PDImageXObject) xobject;
                BufferedImage bImage = image.getImage();
                // 保存或进一步处理图片
                saveImage(bImage, "image_" + pageNumber + "_" + name.getName(), "png");
            }
            if (xobject instanceof PDFormXObject) {
//                PDFormXObject form = (PDFormXObject) xobject;
//                int formType = form.getFormType();
//                InputStream contents = form.getContents();
//                FileUtils.writeByteArrayToFile(new File("output_directory/" + pageNumber + "_" + name.getName() + ".txt"), contents.readAllBytes());
            }
        }
    }

    private static void saveImage(BufferedImage image, String imageName, String format) throws IOException {
        File outputfile = new File("output_directory/" + imageName + "." + format);
        ImageIO.write(image, format, outputfile);
    }
}
